import React, { useState, useEffect, useCallback } from 'react';
import { Flex, Input, Table, Button, Popconfirm, message, Dropdown, Menu, Modal, Splitter,Image } from 'antd';
import { FileExcelOutlined, MoreOutlined } from '@ant-design/icons';
import CopilotChat from '@/components/workbenches/copilot-chat'
import ExcelDetail from './excelDetail';
import { ExcelTableProvider } from '@/components/chat-excel/ExcelTableContext';
import { useTableData,excelParamsInit } from '@/hooks/tableHooks';
import {
  getExcelFileList,
  readExcelFile,
  collectionExcelFile,
  collectionCancelExcelFile,
  collectionBatchExcelFile,
  db_file_refresh,
  recycle_bin,
  recycle_bin_batch,
  deleteBatchExcelFile,
} from '@/client/api'
import { 
  deleteTable,restoreTable} from '@/client/api/smartTable'
import { useRequest } from 'ahooks'
import './table-opacity.css';
const { confirm } = Modal;

interface RecordType {
  id: string;
  collection: number;
  file_name: string;
  user_name: string;
  update_time: string;
  file_size_fm: string;
  create_time: string
}

const ExcelHandle: React.FC<{
  directoryOperationType: string,
  fileOperationObject: { type: string, fileObject: Object },
  copilotStatus: boolean,
  onCopilotStatusChange: (status: boolean) => void;
  collapsed: boolean;
  getCatalogMenusChange: () => void;
}> = (props) => {

  const [copilotVisible, setCopilotVisible] = useState(props.copilotStatus);
  const [currentFile, updateCurrentFile] = useState(null)
  const [copilotFileList, setCopilotFileList] = useState<RecordType[]>([]);
  const [selectedRecord, setSelectedRecord] = useState<RecordType | null>(null);
  const [query_type, setQueryType] = useState<Number | string>('')
  const [sheetName, setSheetName] = useState([])
  const {
    excelParams,
    setExcelParams,
    excelData,
    setExcelData,
    tableType,
    setTableType
  } = useTableData();

  //文件目录操作
  //directoryOperationType  recent 最近 favorite 收藏 myDocuments 我的文档 recycleBin 回收站 add 新建 import 导入
  //文件操作 fileOperationObject type delete 删除 open 打开文件 copy 复制文件 
  useEffect(() => {
    const file = props.fileOperationObject?.fileObject;
    if (file && file.id) {
      updateCurrentFile(file);
      setCopilotFiles(file);
    }

    if (props.fileOperationObject.type) {
      switch (props.fileOperationObject.type) {
        case 'open':
          setExcelParams(() => ({...excelParamsInit}))
          setSelectedRecord(props.fileOperationObject.fileObject)
          readFile(props.fileOperationObject.fileObject) 
          break;
        case 'delete':
          setTableType('list');
          break;
        case 'restore':
          setTableType('list');
          break;
        case 'copy':
          setTableType('list');
          break;
        default:
          break;
      }
    } else if (props.directoryOperationType && props.directoryOperationType != 'import') {
      if (props.directoryOperationType == 'add') {
        setTableType('detail');
      } else {
        setTableType('list');
      }
    }
    const typeMap = {
      recycleBin: 0,
      myDocuments: 1,
      favorite: 2,
      recent: 3,
    };
    const newQueryType = typeMap[props.directoryOperationType as keyof typeof typeMap] ?? '';
    setQueryType(newQueryType);
    getFileList(newQueryType);

  }, [props.fileOperationObject, props.directoryOperationType]);

  // 文件列表
  const { run: getFileList } = useRequest(

    async (type?: any) => {
      let data = {
        'query_type': type !== undefined ? type : query_type,
        key_words: tableParams.key_words || '',
      }
      return await getExcelFileList(data.query_type === '' ? { key_words: tableParams.key_words || '' } : data)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success } = res.data || {}
        // console.log('获取文件列表:', data)
        if (success) {
          setTableData(data)
        }
      }
    }
  )

  // 删除文件
  const { run: deleteFile } = useRequest(
    async (id) => {
      return await recycle_bin({ id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success } = res.data || {}
        if (success) {
          message.success('删除成功');
          getFileList(); // 刷新文件列表
          props.getCatalogMenusChange();
        }
      }
    }
  )
  const { run: deleteTableForever } = useRequest(
    async (id) => {
      return await deleteTable({ id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success, err_msg } = res.data || {}
        if (success) {
          message.success('删除成功');
          getFileList();
          props.getCatalogMenusChange();
        } else {
          message.error(err_msg)
        }
      },
      onError: (err: any) => {
        message.error(err.message);
      },
    }
  )
  // 收藏文件
  const { run: collectionFile } = useRequest(
    async (id) => {
      return await collectionExcelFile({ id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success } = res.data || {}
        if (success) {
          message.success('已收藏');
          getFileList(); // 刷新文件列表
          setSelectedRecord(() => ({ ...selectedRecord, collection: 1 } as any));
        }
      }
    }
  )
  const { run: db_file_refreshRun } = useRequest(
    async (data) => {
      return await db_file_refresh({ ...data })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success } = res.data || {}
        if (success) {
          message.success('已刷新');
          getFileList(); // 刷新文件列表
        }
      }
    }
  )

  // 批量删除文件
  const { run: deleteBatchFile } = useRequest(
    async (ids) => {
      return await recycle_bin_batch(ids)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success } = res.data || {}
        if (success) {
          message.success('删除成功');
          getFileList(); // 刷新文件列表
          props.getCatalogMenusChange();
        }
      }
    }
  )
  // 批量删除文件
  const { run: deleteBatchExcelFileRun } = useRequest(
    async (ids) => {
      return await deleteBatchExcelFile(ids)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success } = res.data || {}
        if (success) {
          message.success('删除成功');
          getFileList(); // 刷新文件列表
          props.getCatalogMenusChange();
        }
      }
    }
  )

  // 批量收藏文件
  const { run: collectionBatchFile } = useRequest(
    async (ids) => {
      return await collectionBatchExcelFile(ids)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success } = res.data || {}
        if (success) {
          message.success('已收藏');
          getFileList(); // 刷新文件列表
        }
      }
    }
  )
   //表格还原
   const { run: restoreTableData } = useRequest(
     async (id) => {
       return await restoreTable({ id })
     },
     {
       manual: true,
       onSuccess: (res: any) => {
         const { data, success, err_msg } = res.data || {}
         if (success) {
           message.success('操作成功')
            getFileList(); // 刷新文件列表
          props.getCatalogMenusChange();
         } else {
           message.error(err_msg)
         }
       }
     }
   )
  // 取消收藏文件
  const { run: collectionCancelFile } = useRequest(
    async (id) => {
      return await collectionCancelExcelFile({ id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success } = res.data || {}
        if (success) {
          message.success('已取消收藏');
          getFileList(); // 刷新文件列表 
          setSelectedRecord(() => ({ ...selectedRecord, collection: 0 } as any));
        }
      }
    }
  )

  // 读取文件
  const { run: readFile } = useRequest(
    async (record) => {
      return await readExcelFile({
        ...excelParams,
        id: record.id
      })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success } = res.data || {}
        // console.log('读取文件:', data)
        if (data) {
          if(props.fileOperationObject.type==='open'){
            setSheetName(data.sheet_names||[])
          }else{
            setSheetName([])
          }
          setExcelData({
            headers: data.headers || [],
            data: data.data || [],
            sheet_names: data.sheet_names || [],
          })
        }
        if (success) {
         setTableType('detail');
        }
      }
    }
  )

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelectedRowKeys(selectedRowKeys)
    },
  };

  const handleCloseCopilot = () => {
    setCopilotVisible(false);
    props.onCopilotStatusChange(false);
  };
  const columns = [
    {
      title: '文件名称',
      dataIndex: 'file_name',
      key: 'file_name',
      // width: 400,
      render: (text: string, record: RecordType) => (
        <div className='flex items-center'>
          <Image src={`/ai/chat_excel_analyze.png`} width={22} height={22} alt='file-icon' preview={false} className='mr-2' style={{minWidth:22}} />
          <Button onClick={() => { 
            setExcelParams(() => ({...excelParamsInit}));
            setSelectedRecord(record); 
            readFile(record); 
          }} className='p-1' type="link">{text}</Button>
        </div>
      ),
      ellipsis: true,
      align: 'left',
      sorter: (a, b) => a.file_name.localeCompare(b.file_name),
    },
    {
      title: '创建人',
      dataIndex: 'user_name',
      key: 'user_name',    
      ellipsis: true,
      align: 'center',
    },
    {
      title: '最近修改',
      dataIndex: 'update_time',
      key: 'update_time',
      ellipsis: true,    
      align: 'center',
      sorter: (a, b) => new Date(a.update_time).getTime() - new Date(b.update_time).getTime(),
    },
    {
      title: '文件大小',
      dataIndex: 'file_size_fm',
      key: 'file_size_fm',
      ellipsis: true,
      align: 'center',
      sorter: (a, b) => a.file_size - b.file_size,
    },
    {
      title: '操作',
      dataIndex: 'operate',   
      key: 'operate',
      fixed: 'right',
      align: 'center',
      width: 240,
      render: (_, record: RecordType) => (
        <div>
          {props.directoryOperationType != 'recycleBin'?<>{record.collection === 1 ? (
            <Button onClick={() => collectionCancelFile(record.id)} type="link">取消收藏</Button>
          ) : (
            <Button onClick={() => collectionFile(record.id)} type="link">收藏</Button>
          )}</>:<><Button onClick={()=>restoreTableData(record.id)} type='link'>还原</Button></>}
       
          <Popconfirm title="确定要删除吗?" onConfirm={() =>{ 
              if(props.directoryOperationType == 'recycleBin'){
                deleteTableForever(record.id)
              }else{
                deleteFile(record.id)
              }
            }} okText="是" cancelText="否">
            <Button type="link">{props.directoryOperationType == 'recycleBin'?'彻底删除':'删除'}</Button>
          </Popconfirm>
          {props.directoryOperationType != 'recycleBin'&&<Dropdown
            overlay={
              <Menu
                onClick={({ key }) => handleMenuClick(key, record)}
                items={[              
                  { label: '刷新', key: 'refresh', disabled: record?.type == 1 ? true : false },//1 excel 2 数据库表
                  { label: '引用到copilot', key: 'refer_copilot' },
                ]}
              />
            }
          >
            <Button type="text">
              <MoreOutlined />
            </Button>
          </Dropdown>}
        </div>
      ),
    },
  ];
  const [tableData, setTableData] = useState<RecordType[]>([])

  const [tableParams, setTableParams] = useState({ key_words: '' })
  useEffect(() => {
    getFileList();
  }, [tableParams])

  const handleMenuClick = (key: string, record: RecordType) => {
    if (key === 'favorite') {
      collectionFile(record.id)
    } else if (key === 'refresh') {
      db_file_refreshRun(record)
    } else if (key === 'refer_copilot') {
      updateCurrentFile(record)
      setCopilotFiles(record)
      setCopilotVisible(true)
    }
  };

  const setCopilotFiles = (file) => {
    if (!file || !file.id) return;
    setCopilotFileList(prevList => {
      const exists = prevList.some(item => item.id === file.id);
      if (!exists) {
        return [...prevList, file];
      }
      return prevList;
    });
  }

  useEffect(() => {
    setCopilotVisible(props.copilotStatus);
  }, [props.copilotStatus]);
  
  return (
    <ExcelTableProvider>
      <div
        className='flex flex-col h-screen w-full overflow-hidden'>
        {tableType == 'detail' ? (
          <ExcelDetail
            collapsed={props.collapsed}
            record={{ ...selectedRecord, directoryType: props.directoryOperationType,sheetName:sheetName}}
            onBack={() => setTableType('list')}
            collectionFile={collectionFile}
            collectionCancelFile={collectionCancelFile}
          />
        ) : (
          <Splitter style={{ height: '100%', boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)' }}>
            <Splitter.Panel defaultSize="55%" min="50%" max="56%">          
              <div className='w-full h-full flex flex-col  flex-auto flex overflow-auto bg-table-excel'>
                <div className='p-4 flex justify-between items-center w-full'>
                  <div className='w-[400px]'>
                    <Input width={120} value={tableParams.key_words}
                      onChange={(e) => setTableParams((v) => ({ ...v, key_words: e.target.value }))} placeholder="查询文档名、创建人" />
                  </div>
                  <div>
                    {props.directoryOperationType != 'recycleBin'&&props.directoryOperationType !='favorite'&&<Button onClick={() => {
                      if (!selectedRowKeys?.length) {
                        message.error('请选择');
                        return
                      }
                      collectionBatchFile(selectedRowKeys)
                    }} type="primary">批量收藏</Button>}
                    <Popconfirm title="确定要删除吗?" onConfirm={() => {
                      if (!selectedRowKeys?.length) {
                        message.error('请选择');
                        return
                      }
                      if(props.directoryOperationType == 'recycleBin'){
                        deleteBatchExcelFileRun(selectedRowKeys)
                      }else{
                        deleteBatchFile(selectedRowKeys)
                      }
                    }} okText="是" cancelText="否">
                      <Button type="primary" className='ml-2'>批量{props.directoryOperationType == 'recycleBin'?'彻底删除':'删除'}</Button>
                    </Popconfirm>
                  </div>
                </div>
                <div className='w-[99%] p-4 h-full transparent-bg-wrap'>
                  <Table className="transparent-bg-table" rowKey="id" dataSource={tableData} rowSelection={rowSelection} columns={columns} pagination={false} scroll={{ y: 'calc(100vh - 250px)' }} />
                </div>
              </div>          
            </Splitter.Panel>
            { copilotVisible && (
                <Splitter.Panel>
                  <CopilotChat 
                    setCopilotVisible={handleCloseCopilot}                 
                    chat_scene={'chat_excel_analyze'} 
                    copilotType={'EXCEL_ANALYZE'}
                    fileId={currentFile?.id}
                    copilotFileList={copilotFileList}
                  />
                </Splitter.Panel>
                ) 
              }
          </Splitter>
        )}
      </div>
    </ExcelTableProvider>
  );
};

export default ExcelHandle;